﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Bamboo.Core.Data;

namespace TinyERP.Framework.Controls
{
    public class InvalidSearchInputControlException : ApplicationException
    {
        public InvalidSearchInputControlException(string message)
            : base(message)
        {

        }
    }
    public class SearchController
    {
        
        protected IList<Control> searchInputControls;
        public SearchController()
        {
            searchInputControls = new List<Control>();
        }

        public void AddSearchInputControl(Control control)
        {
            if (!(control.Tag is SearchCondition))
            {
                string exceptionMessage = "Control " + control.Name + " is not a search input control. Tag of search input control must be SearchCondition type";
                InvalidSearchInputControlException exception = new InvalidSearchInputControlException(exceptionMessage);
                
                throw exception;
            }
            searchInputControls.Add(control);
        }
        public IList<SearchCondition> GetSearchConditions()
        {
            IList<SearchCondition> searchConditions = new List<SearchCondition>();
            foreach (Control control in searchInputControls)
            {
                string valueOfControl = GetValueOfControl(control);
                if (!string.IsNullOrEmpty(valueOfControl))
                {
                    SearchCondition condition = (control.Tag as SearchCondition).Clone();
                    condition.SearchParameterValue = valueOfControl;
                    searchConditions.Add(condition);
                }
            }
            return searchConditions;
        }

        protected string GetValueOfControl(Control control)
        {
            if (control is TextBox || control is RichTextBox)
            {
                return control.Text.Trim();
            }
            else if (control is ComboBox)
            {
                if (((ComboBox)control).SelectedValue == null)
                {
                    return null;
                }
                return  ((ComboBox)control).SelectedValue.ToString();
            }
            return null;
        }
    }
}
